import { useEffect, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { generateSudokuPuzzle } from '../utils/sudokuUtils';
import { renderSudokuGrid } from './SudokuRenderer';

const WhiteBoard = () => {
  const location = useLocation();
  const [roomId, setRoomId] = useState(null);
  const [ws, setWs] = useState(null);
  const drawingRef = useRef(false);
  const canvasRef = useRef(null);
  const [isDrawing, setIsDrawing] = useState(false);
  const [context, setContext] = useState(null);
  const [currentColor, setCurrentColor] = useState('#000000');
  const [history, setHistory] = useState([]);
  const [sudokuSize, setSudokuSize] = useState(6); // 添加数独大小状态

  const handleColorChange = (e) => {
    const newColor = e.target.value;
    setCurrentColor(newColor);
    if (context) {
      context.strokeStyle = newColor;
    }
  };

  const saveState = () => {
    if (!canvasRef.current) return;
    const canvas = canvasRef.current;
    const imageData = canvas.toDataURL('image/png');
    setHistory(prev => [...prev, imageData]);

    // Send drawing state to server if connected
    if (ws && roomId) {
      ws.send(JSON.stringify({
        type: 'draw',
        data: imageData,
        roomId: roomId
      }));
    }
  };

  const undo = () => {
    if (history.length === 0) return;
    
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const img = new Image();
    
    img.onload = () => {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.drawImage(img, 0, 0);
      
      // 发送回退操作到服务器
      if (ws && roomId) {
        const previousState = history[history.length - 2];
        ws.send(JSON.stringify({
          type: 'undo',
          data: previousState || '',  // 如果没有前一个状态，发送空字符串
          roomId: roomId,
          timestamp: Date.now()
        }));
      }
    };
    
    const previousState = history[history.length - 2];
    if (previousState) {
      img.src = previousState;
      setHistory(prev => prev.slice(0, -1));
    } else {
      ctx.fillStyle = '#FFFFFF';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      setHistory([]);
    }
  };

  // 添加清除画布函数
  const clearCanvas = () => {
    if (!canvasRef.current || !context) return;
    
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    
    // 清除整个画布
    ctx.fillStyle = '#FFFFFF';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 保存清除后的状态
    saveState();
    
    // 如果连接了WebSocket，发送清除操作
    if (ws && roomId) {
      ws.send(JSON.stringify({
        type: 'clear',
        roomId: roomId,
        timestamp: Date.now()
      }));
    }
  };

  useEffect(() => {
    const initRoom = async () => {
      const params = new URLSearchParams(location.search);
      let currentRoomId = params.get('room');

      if (!currentRoomId) {
        const protocol = window.location.protocol;
        const host = window.location.hostname;
        const port = '8001';
        const createRoomUrl = `${protocol}//${host}:${port}/create-room`;
        
        console.log('创建房间URL:', createRoomUrl);
        
        try {
          const response = await fetch(createRoomUrl, {
            method: 'GET',
            headers: {
              'Accept': 'application/json',
              'Origin': window.location.origin,
            },
            mode: 'cors',
            credentials: 'omit',
          });
          
          if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
          }
          
          const data = await response.json();
          currentRoomId = data.room_id;
          window.history.pushState({}, '', `?room=${currentRoomId}`);
        } catch (error) {
          console.error('创建房间失败:', error);
          alert(`创建房间失败: ${error.message}\n请检查服务器是否正常运行`);
          return;
        }
      }

      setRoomId(currentRoomId);

      // 添加连接状态日志
      console.log('正在连接到房间:', currentRoomId);
      
      const wsProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
      const wsHost = window.location.hostname;
      const wsPort = '8001';  // 使用后端端口
      const wsUrl = `${wsProtocol}//${wsHost}:${wsPort}/ws/${currentRoomId}`;
      
      console.log('WebSocket URL:', wsUrl);
      
      const wsConnection = new WebSocket(wsUrl);
      
      wsConnection.onopen = () => {
        console.log('WebSocket连接已建立');
        // 连接建立后立即发送ready消息
        wsConnection.send(JSON.stringify({
          type: 'client_ready',
          roomId: currentRoomId
        }));
      };
      
      wsConnection.onclose = () => {
        console.log('WebSocket连接已关闭');
      };
      
      wsConnection.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };

      wsConnection.onmessage = (event) => {
        try {
          const message = JSON.parse(event.data);
          console.log('收到消息:', message.type);
          
          if (message.type === 'init_start') {
            console.log('开始接收初始状态');
          } 
          else if (message.type === 'init_chunk') {
            console.log('接收状态块:', message.chunk_index);
            const canvas = canvasRef.current;
            const ctx = canvas.getContext('2d');
            
            message.data.forEach(state => {
              if (state.type === 'draw' && state.data) {
                const img = new Image();
                img.onload = () => {
                  ctx.drawImage(img, 0, 0);
                };
                img.src = state.data;
              }
            });
          }
          else if (message.type === 'init_complete') {
            console.log('初始状态接收完成');
          }
          else if (message.type === 'draw' && !drawingRef.current) {
            console.log('接收到新的绘画数据');
            const canvas = canvasRef.current;
            const ctx = canvas.getContext('2d');
            const img = new Image();
            img.onload = () => {
              ctx.drawImage(img, 0, 0);
            };
            img.src = message.data;
          }
          else if (message.type === 'undo' && !drawingRef.current) {
            console.log('接收到回退操作');
            const canvas = canvasRef.current;
            const ctx = canvas.getContext('2d');
            
            if (message.data) {
              const img = new Image();
              img.onload = () => {
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(img, 0, 0);
              };
              img.src = message.data;
            } else {
              // 如果没有前一个状态，清空画布
              ctx.fillStyle = '#FFFFFF';
              ctx.fillRect(0, 0, canvas.width, canvas.height);
            }
            
            setHistory(prev => prev.slice(0, -1));
          }
          // 添加清除画布消息的处理
          if (message.type === 'clear' && !drawingRef.current) {
            console.log('接收到清除画布操作');
            const canvas = canvasRef.current;
            const ctx = canvas.getContext('2d');
            ctx.fillStyle = '#FFFFFF';
            ctx.fillRect(0, 0, canvas.width, canvas.height);
            setHistory([]); // 清空历史记录
          }
        } catch (error) {
          console.error('处理消息时出错:', error);
        }
      };

      setWs(wsConnection);
    };

    initRoom();

    return () => {
      if (ws) {
        console.log('关闭WebSocket连接');
        ws.close();
      }
    };
  }, [location]);

  useEffect(() => {
    const canvas = canvasRef.current;
    const updateCanvasSize = () => {
      // 保存当前画布内容
      const prevCanvas = document.createElement('canvas');
      const prevCtx = prevCanvas.getContext('2d');
      prevCanvas.width = canvas.width;
      prevCanvas.height = canvas.height;
      prevCtx.drawImage(canvas, 0, 0);

      // 计算新的画布尺寸
      const viewportWidth = window.innerWidth;
      const viewportHeight = window.innerHeight;
      
      // 使用固定的容器宽度比例
      const containerWidth = viewportWidth * 0.9;  // 使用90%的视口宽度
      const containerHeight = viewportHeight * 0.8; // 使用80%的视口高度
      
      // 保持4:3的宽高比
      const aspectRatio = 4/3;
      let newWidth, newHeight;
      
      if (containerWidth / aspectRatio <= containerHeight) {
        // 以容器宽度为基准
        newWidth = containerWidth;
        newHeight = containerWidth / aspectRatio;
      } else {
        // 以容器高度为基准
        newHeight = containerHeight;
        newWidth = containerHeight * aspectRatio;
      }
      
      // 应用最大限制
      newWidth = Math.min(newWidth, 1200);
      newHeight = Math.min(newHeight, 900);
      
      // 应用新尺寸
      canvas.width = newWidth;
      canvas.height = newHeight;
      
      // 重新绘制内容
      const ctx = canvas.getContext('2d');
      ctx.fillStyle = '#FFFFFF';
      ctx.fillRect(0, 0, canvas.width, canvas.height);
      
      // 保持绘制内容的比例
      const scale = Math.min(
        newWidth / prevCanvas.width,
        newHeight / prevCanvas.height
      );
      
      const x = (newWidth - prevCanvas.width * scale) / 2;
      const y = (newHeight - prevCanvas.height * scale) / 2;
      
      ctx.drawImage(
        prevCanvas,
        x, y,
        prevCanvas.width * scale,
        prevCanvas.height * scale
      );

      // 重置绘图上下文的样式
      ctx.strokeStyle = currentColor;
      ctx.lineWidth = 2;
      ctx.lineCap = 'round';
    };

    if (!context) {
      updateCanvasSize();
      window.addEventListener('resize', updateCanvasSize);
      const ctx = canvas.getContext('2d');
      setContext(ctx);
      saveState();
    } else {
      context.strokeStyle = currentColor;
    }

    return () => window.removeEventListener('resize', updateCanvasSize);
  }, [currentColor, context]);

  const getCoordinates = (e) => {
    const rect = canvasRef.current.getBoundingClientRect();
    if (e.touches && e.touches.length > 0) {
      return {
        x: e.touches[0].clientX - rect.left,
        y: e.touches[0].clientY - rect.top
      };
    }
    // 对于鼠标事件，也使用相对于画布的坐标计算
    return {
      x: e.clientX - rect.left,
      y: e.clientY - rect.top
    };
  };

  const startDrawing = (e) => {
    if (!context) return;
    drawingRef.current = true; // 设置绘画状态
    const { x, y } = getCoordinates(e);
    context.beginPath();
    context.moveTo(x, y);
    setIsDrawing(true);
  };

  const draw = (e) => {
    if (!isDrawing || !context) return;
    const { x, y } = getCoordinates(e);
    context.lineTo(x, y);
    context.stroke();
  };

  const stopDrawing = () => {
    if (!context) return;
    drawingRef.current = false; // 清除绘画状态
    context.closePath();
    setIsDrawing(false);
    saveState();
  };

  const generateSudokuGrid = () => {
    const grid = generateSudokuPuzzle(sudokuSize, Math.floor(sudokuSize * sudokuSize / 3));
    
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    
    // 保存当前画布状态
    const imageData = canvas.toDataURL('image/png');
    
    // 清除画布
    ctx.fillStyle = '#FFFFFF';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 计算数独网格的大小和位置
    const minDimension = Math.min(canvas.width, canvas.height);
    const gridSize = minDimension * 0.8;
    
    // 使用renderSudokuGrid渲染数独网格
    renderSudokuGrid(ctx, canvas, grid, 0, 0, gridSize);
    
    // 保存最终状态并发送到服务器
    saveState();
  };

  // 添加数独大小选择处理函数
  const handleSizeChange = (e) => {
    const newSize = parseInt(e.target.value);
    setSudokuSize(newSize);
  };

  // 添加useEffect来设置文档标题
  useEffect(() => {
    document.title = '在线白板';
  }, []);

  // 修改水墨风格的背景样式
  const containerStyle = {
    background: 'linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%)',  // 更柔和的渐变背景
    width: '100vw',
    height: '100vh',
    position: 'relative',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    overflow: 'hidden'
  };

  // 修改canvas样式
  const canvasStyle = {
    border: '1px solid rgba(0, 0, 0, 0.1)',  // 更细腻的边框
    touchAction: 'none',
    WebkitTouchCallout: 'none',
    WebkitUserSelect: 'none',
    userSelect: 'none',
    backgroundColor: '#ffffff',  // 纯白背景
    boxShadow: '0 8px 30px rgba(0, 0, 0, 0.05), 0 2px 8px rgba(0, 0, 0, 0.02)',  // 更柔和的阴影
    borderRadius: '12px'  // 更大的圆角
  };

  // 工具项容器样式
  const toolItemStyle = {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    marginBottom: '16px'
  };

  // 工具文字描述样式
  const toolLabelStyle = {
    fontSize: '12px',
    color: '#64748b',  // 更柔和的文字颜色
    marginTop: '4px',
    textAlign: 'center',
    userSelect: 'none'
  };

  // 工具栏容器样式
  const toolbarStyle = {
    position: 'absolute',
    left: '20px',
    top: '50%',
    transform: 'translateY(-50%)',
    background: 'rgba(255, 255, 255, 0.85)',  // 更透明的背景
    padding: '16px 12px',
    borderRadius: '16px',  // 更大的圆角
    backdropFilter: 'blur(10px)',  // 毛玻璃效果
    WebkitBackdropFilter: 'blur(10px)',  // Safari 支持
    boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05), 0 2px 8px rgba(0, 0, 0, 0.02)',  // 更精致的阴影
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: '8px',
    zIndex: 1000,
    border: '1px solid rgba(255, 255, 255, 0.3)'  // subtle border
  };

  // 主内容区样式
  const mainContentStyle = {
    flex: '1',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    padding: '20px 60px'  // 左侧留出工具栏的空间
  };

  // 数独选择器包装器样式
  const sudokuSelectorStyle = {
    position: 'relative',
    width: '40px',
    height: '40px',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    marginBottom: '16px'
  };

  // 按钮和选择器样式更新
  const buttonStyle = "w-10 h-10 bg-white/80 border border-gray-200 rounded-lg text-gray-700 hover:bg-white hover:shadow-md transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-200 flex items-center justify-center text-lg";
  const selectStyle = "w-10 h-10 bg-white/80 border border-gray-200 rounded-lg text-gray-700 text-xs hover:bg-white focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-200 cursor-pointer appearance-none px-1";
  const colorPickerStyle = "w-10 h-10 p-1 bg-white/80 border border-gray-200 rounded-lg cursor-pointer hover:shadow-md focus:outline-none focus:ring-2 focus:ring-blue-100 focus:border-blue-200";

  return (
    <div style={containerStyle}>
      {/* 左侧工具栏 */}
      <div style={toolbarStyle}>
        <div style={toolItemStyle}>
          <input
            type="color"
            value={currentColor}
            onChange={handleColorChange}
            className={colorPickerStyle}
            title="选择颜色"
          />
          <span style={toolLabelStyle}>颜色</span>
        </div>

        <div style={toolItemStyle}>
          <button 
            onClick={undo} 
            className={buttonStyle}
            title="撤销"
          >
            ↩
          </button>
          <span style={toolLabelStyle}>撤销</span>
        </div>

        <div style={sudokuSelectorStyle}>
          <select
            value={sudokuSize}
            onChange={handleSizeChange}
            className={selectStyle}
            title="数独大小"
          >
            <option value="4">4×4</option>
            <option value="6">6×6</option>
            <option value="9">9×9</option>
          </select>
          <span style={toolLabelStyle}>大小</span>
        </div>

        <div style={toolItemStyle}>
          <button 
            onClick={generateSudokuGrid} 
            className={buttonStyle}
            title="生成数独"
          >
            ⊞
          </button>
          <span style={toolLabelStyle}>生成</span>
        </div>

        <div style={toolItemStyle}>
          <button 
            onClick={clearCanvas} 
            className={buttonStyle}
            title="清除画布"
          >
            ⌫
          </button>
          <span style={toolLabelStyle}>清除</span>
        </div>
      </div>

      {/* 主画布区域 */}
      <div style={mainContentStyle}>
        <canvas
          ref={canvasRef}
          onMouseDown={startDrawing}
          onMouseMove={draw}
          onMouseUp={stopDrawing}
          onMouseOut={stopDrawing}
          onTouchStart={startDrawing}
          onTouchMove={draw}
          onTouchEnd={stopDrawing}
          onTouchCancel={stopDrawing}
          style={canvasStyle}
        />
      </div>
    </div>
  );
};

export default WhiteBoard;